package com.aisile.aliyun.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainTestsNews {

    public static void main(String[] args) throws Exception {
        /**
         * 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。 
         * 常见获取环境变量方式：
         * 方式一：
         *     获取RAM用户AccessKey ID：System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret：System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * 方式二：
         *     获取RAM用户AccessKey ID：System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     获取RAM用户AccessKey Secret：System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         *
         *         String accessKey = "LTAI5tCDV5mGiEsKesvfs9zf";
         *     String secretKey = "ggA56OT8SiTBkvKFkZdmGgx5gIyg0L";
         *
         *
         *
         *
         *
         *
         *     {
         * 	"scenes":[
         * 		"antispam"
         * 	],
         * 	"tasks":[
         *                {
         * 			"dataId":"18b10570-417e-4695-af45-4b0ecbcfd3f7",
         * 			"content":"五千年的风和雨啊,藏了多少梦,黄色的脸黑色的眼,不变是笑容,八千里山川河岳"
         *        }
         * 	]
         * }
         * {
         * 	"msg":"OK",
         * 	"code":200,
         * 	"data":[
         *        {
         * 			"msg":"OK",
         * 			"code":200,
         * 			"dataId":"18b10570-417e-4695-af45-4b0ecbcfd3f7",
         * 			"results":[
         *                {
         * 					"rate":99.91,
         * 					"suggestion":"pass",
         * 					"label":"normal",
         * 					"scene":"antispam"
         *                }
         * 			],
         * 			"content":"五千年的风和雨啊,藏了多少梦,黄色的脸黑色的眼,不变是笑容,八千里山川河岳",
         * 			"taskId":"txt5VkOrgdc4Ys40nrOLKRWxU-1zeMa@"
         *        }
         * 	],
         * 	"requestId":"B29BC1BF-8287-5B04-A3FB-598280137767"
         * }
         * args = [antispam]
         * args = [pass]
         *
         *
         * {
         * 	"scenes":[
         * 		"antispam"
         * 	],
         * 	"tasks":[
         *                {
         * 			"dataId":"37b1a899-4c5d-4ea0-86bc-e159068fab7d",
         * 			"content":"本校小额贷款，安全、快捷、方便、无抵押，随机随贷，当天放款，上门服务。"
         *        }
         * 	]
         * }
         * {
         * 	"msg":"OK",
         * 	"code":200,
         * 	"data":[
         *        {
         * 			"msg":"OK",
         * 			"code":200,
         * 			"dataId":"37b1a899-4c5d-4ea0-86bc-e159068fab7d",
         * 			"results":[
         *                {
         * 					"rate":100.0,
         * 					"suggestion":"block",
         * 					"details":[
         *                        {
         * 							"label":"contraband"
         *                        }
         * 					],
         * 					"label":"contraband",
         * 					"scene":"antispam"
         *                }
         * 			],
         * 			"content":"本校小额贷款，安全、快捷、方便、无抵押，随机随贷，当天放款，上门服务。",
         * 			"taskId":"txt7t0tLHwwXmL7VZDVuRDu40-1zeMi2",
         * 			"filteredContent":"本校****，安全、快捷、方便、无抵押，****，当天放款，****。"
         *        }
         * 	],
         * 	"requestId":"008FACFA-C475-573F-8ED5-AC760F5B03C2"
         * }
         * args = [antispam]
         * args = [block]
         *
         *
         * {
         * 	"scenes":[
         * 		"antispam"
         * 	],
         * 	"tasks":[
         *                {
         * 			"dataId":"5bd22753-c92c-4731-9775-10888368bae7",
         * 			"content":"我不吸毒，我也不能让我身边的人吸毒"
         *        }
         * 	]
         * }
         * {
         * 	"msg":"OK",
         * 	"code":200,
         * 	"data":[
         *        {
         * 			"msg":"OK",
         * 			"code":200,
         * 			"dataId":"5bd22753-c92c-4731-9775-10888368bae7",
         * 			"results":[
         *                {
         * 					"rate":99.91,
         * 					"suggestion":"block",
         * 					"details":[
         *                        {
         * 							"contexts":[
         *                                {
         * 									"context":"吸毒",
         * 									"positions":[
         *                                        {
         * 											"startPos":2,
         * 											"endPos":4
         *                                        },
         *                                        {
         * 											"startPos":15,
         * 											"endPos":17
         *                                        }
         * 									]
         *                                }
         * 							],
         * 							"label":"contraband"
         *                        }
         * 					],
         * 					"label":"contraband",
         * 					"scene":"antispam"
         *                }
         * 			],
         * 			"content":"我不吸毒，我也不能让我身边的人吸毒",
         * 			"taskId":"txt34kHj$oFHQ051hLzj1dTVy-1zeMjm",
         * 			"filteredContent":"我不**，我也不能让我身边的人**"
         *        }
         * 	],
         * 	"requestId":"50E75644-9D2B-5C7A-9EC9-37A80C0ED64D"
         * }
         * args = [antispam]
         * args = [block]
         *
         *
         * {
         * 	"scenes":[
         * 		"antispam"
         * 	],
         * 	"tasks":[
         *                {
         * 			"dataId":"29bb6913-8735-4aae-ac49-8803c4593c22",
         * 			"content":"俏丽哇,你是傻波一，真TM无语！病毒"
         *        }
         * 	]
         * }
         * {
         * 	"msg":"OK",
         * 	"code":200,
         * 	"data":[
         *        {
         * 			"msg":"OK",
         * 			"code":200,
         * 			"dataId":"29bb6913-8735-4aae-ac49-8803c4593c22",
         * 			"results":[
         *                {
         * 					"rate":99.91,
         * 					"suggestion":"block",
         * 					"details":[
         *                        {
         * 							"contexts":[
         *                                {
         * 									"libCode":"12786001",
         * 									"libName":"安抚",
         * 									"context":"俏丽哇",
         * 									"positions":[
         *                                        {
         * 											"startPos":0,
         * 											"endPos":3
         *                                        }
         * 									]
         *                                },
         *                                {
         * 									"libCode":"12786001",
         * 									"libName":"安抚",
         * 									"context":"病毒",
         * 									"positions":[
         *                                        {
         * 											"startPos":16,
         * 											"endPos":18
         *                                        }
         * 									]
         *                                }
         * 							],
         * 							"label":"customized"
         *                        }
         * 					],
         * 					"label":"customized",
         * 					"scene":"antispam"
         *                }
         * 			],
         * 			"content":"俏丽哇,你是傻波一，真TM无语！病毒",
         * 			"taskId":"txt6jqskP2OAxC7pFYCJBpB3H-1zeMob",
         * 			"filteredContent":"***,你是傻波一，真TM无语！**"
         *        }
         * 	],
         * 	"requestId":"4AA7EC7D-B0DA-54E4-9A7B-8FC2D567FB38"
         * }
         * args = [antispam]
         * args = [block]
         *
         *
         */

        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "LTAI5tCDV5mGiEsKesvfs9zf",
                "ggA56OT8SiTBkvKFkZdmGgx5gIyg0L");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // 注意：此处实例化的client尽可能重复使用，提升检测性能。避免重复建立连接。
        IAcsClient client = new DefaultAcsClient(profile);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId("cn-shanghai");
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();

        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符。
         */
        task1.put("content", "俏丽哇,你是傻波一，真TM无语！病毒");
        tasks.add(task1);

        JSONObject data = new JSONObject();

        /**
         * 检测场景。文本垃圾检测请传递antispam。
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        System.out.println(JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间。
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(textScanRequest);
            if (!httpResponse.isSuccess()) {
                System.out.println("response not success. status:" + httpResponse.getStatus());
                // 业务处理。
                return;
            }
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
            System.out.println(JSON.toJSONString(scrResponse, true));
            if (200 != scrResponse.getInteger("code")) {
                System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                // 业务处理。
                return;
            }
            JSONArray taskResults = scrResponse.getJSONArray("data");
            for (Object taskResult : taskResults) {
                if (200 != ((JSONObject) taskResult).getInteger("code")) {
                    System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                    // 业务处理。
                    continue;
                }
                JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                for (Object sceneResult : sceneResults) {
                    String scene = ((JSONObject) sceneResult).getString("scene");
                    String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                    // 根据scene和suggestion做相关处理。
                    // suggestion为pass表示未命中垃圾。suggestion为block表示命中了垃圾，可以通过label字段查看命中的垃圾分类。
                    System.out.println("args = [" + scene + "]");
                    System.out.println("args = [" + suggestion + "]");
                }
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}